package model

import (
	"context"
	"fmt"

	"github.com/Masterminds/squirrel"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

var _ SysRoleMenuModel = (*customSysRoleMenuModel)(nil)

type (
	// SysRoleMenuModel is an interface to be customized, add more methods here,
	// and implement the added methods in customSysRoleMenuModel.
	SysRoleMenuModel interface {
		sysRoleMenuModel
		withSession(session sqlx.Session) SysRoleMenuModel
		TransDelete(ctx context.Context, session sqlx.Session, roleId int64) error
		TransInsertBatch(ctx context.Context, session sqlx.Session, list []SysRoleMenu) error
	}

	customSysRoleMenuModel struct {
		*defaultSysRoleMenuModel
	}
)

// NewSysRoleMenuModel returns a model for the database table.
func NewSysRoleMenuModel(conn sqlx.SqlConn) SysRoleMenuModel {
	return &customSysRoleMenuModel{
		defaultSysRoleMenuModel: newSysRoleMenuModel(conn),
	}
}

func (m *customSysRoleMenuModel) withSession(session sqlx.Session) SysRoleMenuModel {
	return NewSysRoleMenuModel(sqlx.NewSqlConnFromSession(session))
}

func (m *customSysRoleMenuModel) TransDelete(ctx context.Context, session sqlx.Session, roleId int64) error {
	query := fmt.Sprintf("delete from %s where `role_id` = ?", m.table)
	_, err := session.ExecCtx(ctx, query, roleId)
	return err
}

// 批量保存
func (m *customSysRoleMenuModel) TransInsertBatch(ctx context.Context, session sqlx.Session, list []SysRoleMenu) error {

	sqlBuilder := squirrel.Insert(m.table).Columns("role_id", "menu_id")

	for _, v := range list {
		sqlBuilder = sqlBuilder.Values(v.RoleId, v.MenuId)
	}

	query, args, err := sqlBuilder.ToSql()
	if err != nil {
		return err
	}

	_, err = session.ExecCtx(ctx, query, args...)

	return err
}
